package com.arm.controller.pay;

import com.arm.controller.WechatBaseController;
import com.arm.def.Constant;
import com.arm.module.*;
import com.arm.service.ConsigneeInfoService;
import com.arm.service.OrderService;
import com.arm.service.PayService;
import com.arm.tools.myRunTime.MyRunTimeExcption;
import com.arm.tools.result.ResultObj;
import com.arm.tools.result.ReturnCode;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.HashMap;
import java.util.Map;

/**
 * Created by baggio on 2016/12/29.
 */
@RequestMapping("/pay")
@RestController
public class PayController extends WechatBaseController {

    @Autowired
    private OrderService orderService;
    @Autowired
    private PayService weChatPayService;
    @Autowired
    private ConsigneeInfoService consigneeInfoService;

    @PostMapping(value = "/toPay")
    public String toPay(HttpServletRequest request, Long orderId, Payment payment, ConsigneeInfo consigneeInfo) {
        ResultObj resultObj = new ResultObj();
        PayParameter payParameter = null;
        try {
            if (super.getIsMobile(super.httpServletRequest)) {
                super.oauth2(super.httpServletRequest, super.httpServletResponse);
            }
            User user = (User) request.getSession().getAttribute(Constant.SESSION_KEY_USER_LOGIN);
            if (user == null) {
                throw new MyRunTimeExcption("用户没有登录！");
            }
            String remoteAddr = request.getRemoteAddr();
            System.out.println("remoteAddr===>" + remoteAddr);
            String openid = user.getOpenId();
            logger.info("openId===>" + openid);
            consigneeInfoService.modifyConsigneeInfo(consigneeInfo);
            payParameter = orderService.toPay(orderId, payment, remoteAddr, openid);
            resultObj.setData(payParameter);
            logger.info("payParameter===>" + payParameter.toString());
        } catch (MyRunTimeExcption runTimeExcption) {
            logger.info(runTimeExcption.getMessage());
            resultObj.setCode(ReturnCode.FAIL.getCode());
            resultObj.setMsg(runTimeExcption.getMessage());
            runTimeExcption.printStackTrace();
        } catch (Exception e) {
            logger.info(e.getMessage());
            e.printStackTrace();
            resultObj.setCode(ReturnCode.FAIL.getCode());
            resultObj.setMsg(e.getMessage());

        }


        //   return "redirect:" + bankUrl;
        //return new RedirectView(payParameter.getBankUrl(),true,false,false);//最后的参数为false代表以post方式提交请求
        //return new ModelAndView(new RedirectView(payParameter.getBankUrl()), payParameter.getMap());
        return resultObj.toJson();
    }



    /**
     * 客户支付后微信的回调接口
     *
     * @param request
     * @return
     */
    @RequestMapping(value = "/notification")
    @ResponseBody
    public String notification(HttpServletRequest request) {

        InputStream inputStream = null;
        BufferedReader bufferedReader = null;

        try {
            inputStream = request.getInputStream();
            bufferedReader = new BufferedReader(new InputStreamReader(inputStream, "UTF-8"));

            String str;
            StringBuilder xmlString = new StringBuilder();
            while ((str = bufferedReader.readLine()) != null) {
                xmlString.append(str);
            }
            try {
                bufferedReader.close();
                inputStream.close();
            } catch (IOException e) {
                e.printStackTrace();
            }

            Map<String, String> xml = new HashMap<String, String>();
            xml.put("xml", xmlString.toString());
            Map<String, String> returnMap = weChatPayService.notification(xml);
            return returnMap.get("xml");
        } catch (IOException e) {
            e.printStackTrace();
            return null;
        }

    }


    @RequestMapping(value = "/{orderId}")
    public ModelAndView pay(@PathVariable("orderId") Long orderId) {        // source: 1(来源于网站) | 2(来源于微站)
        ModelAndView mov = new ModelAndView();


        Order order = orderService.getOrderById(orderId);
        mov.addObject("order", order);
        mov.setViewName("weChat/pay/pay");
        return mov;
    }

    /**
     * 支付结果
     *
     * @param errorStr
     * @param errorCode
     * @return
     */
    @RequestMapping(value = "/payResult")
    public ModelAndView paySuccess(HttpServletRequest request, String errorStr, String errorCode, Long ordrId) {
        // source: 1(来源于网站) | 2(来源于微站)
        ModelAndView mov = new ModelAndView();
        mov.setViewName("web/pay/payResult");
        if (super.getIsMobile(request)) {
            mov.setViewName("weChat/pay/payResult");
        }
        Order order = orderService.getOrderById(ordrId);
        mov.addObject("errorStr", errorStr);
        mov.addObject("errorCode", errorCode);
        mov.addObject("order", order);
        return mov;
    }

    //将前缀为consigneeInfo.的属性绑定到 名称为consigneeInfo的对象
    @InitBinder("consigneeInfo")
    public void initBinder2(WebDataBinder binder) {
        binder.setFieldDefaultPrefix("consigneeInfo.");
    }
}
